package cn.ygh.bbo.system.sdk.shiro;

import cn.ygh.bbo.common.exception.LoginException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;


/**
 * @author ygh
 * @Desc Shiro通用工具
 * @date 2019/2/17 13:35
 */
public class ShiroUtils {

    /**
     * 用户登陆信息注销
     *
     * @param
     * @return
     */
    public static Session getSession() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            return subject.getSession(false);
        }
        return null;
    }

    /**
     * 获得用户登陆信息
     *
     * @param <T>
     * @return
     */
    public static <T> T getPrincipal() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            return (T) subject.getPrincipal();
        } else {
            return null;
        }
    }


    /**
     * 获得用户登陆信息 失败的话带异常
     *
     * @param <T>
     * @return
     */
    public static <T> T getPrincipalWithException() throws LoginException {
        T sessionUser = getPrincipal();
        if (sessionUser == null) {
            throw new LoginException("请先登陆");
        }
        return sessionUser;
    }

    /**
     * 用户登陆信息注销
     *
     * @param
     * @return
     */
    public static void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
    }
}
